package com.wdb007.venus.web.api.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.wdb007.venus.svc.biz.manager.ConfigInfoManager;
import com.wdb007.venus.svc.biz.utils.ShareImageUtil;
import com.wdb007.venus.svc.facade.BookInfoService;
import com.wdb007.venus.svc.facade.BookShelfService;
import com.wdb007.venus.svc.facade.BookgridService;
import com.wdb007.venus.svc.facade.UserService;
import com.wdb007.venus.svc.facade.book.model.BRBookDTO;
import com.wdb007.venus.svc.facade.book.model.BorrowedHistVO;
import com.wdb007.venus.svc.facade.book.model.BorrowingBook;
import com.wdb007.venus.svc.facade.book.model.BorrowingBookDTO;
import com.wdb007.venus.svc.facade.book.model.UserBorrowPageDTO;
import com.wdb007.venus.svc.facade.constant.RspCodeEnum;
import com.wdb007.venus.svc.facade.exception.BizException;
import com.wdb007.venus.svc.facade.model.VenusSvcResp;
import com.wdb007.venus.svc.facade.user.model.DeviceUpgradeFlagDTO;
import com.wdb007.venus.svc.facade.user.model.RankListPageQueryDTO;
import com.wdb007.venus.svc.facade.user.model.RankListPageResultDTO;
import com.wdb007.venus.svc.facade.user.model.ReportAbnormalDTO;
import com.wdb007.venus.svc.facade.user.model.SmsVerifactionDTO;
import com.wdb007.venus.svc.facade.user.model.UserAccessLogDTO;
import com.wdb007.venus.svc.facade.user.model.UserActiveDTO;
import com.wdb007.venus.svc.facade.user.model.UserDespositCashStatusDTO;
import com.wdb007.venus.svc.facade.user.model.UserEntiretyDTO;
import com.wdb007.venus.svc.facade.user.model.UserFamilyMemberDTO;
import com.wdb007.venus.svc.facade.user.model.UserInfoDTO;
import com.wdb007.venus.svc.facade.user.model.UserInviteInfoDTO;
import com.wdb007.venus.svc.facade.user.model.UserLastestInfoDTO;
import com.wdb007.venus.svc.facade.user.model.UserQueryDTO;
import com.wdb007.venus.svc.facade.user.model.UserRankDTO;
import com.wdb007.venus.svc.facade.user.model.WeekRankInfoDTO;
import com.wdb007.venus.svc.facade.user.model.WeekRankPersonInfoDTO;
import com.wdb007.venus.svc.facade.user.model.WishListDTO;
import com.wdb007.venus.svc.facade.user.model.WishListPageQueryDTO;
import com.wdb007.venus.svc.facade.user.model.WishListPageResultDTO;
import com.wdb007.venus.svc.facade.user.model.WishListResultDTO;
import com.wdb007.venus.web.api.book.model.BRBookVO;
import com.wdb007.venus.web.api.book.model.BorrowingBookVO;
import com.wdb007.venus.web.api.model.BaseResponse;
import com.wdb007.venus.web.api.user.model.ActiveRequest;
import com.wdb007.venus.web.api.user.model.DeviceTypeRequest;
import com.wdb007.venus.web.api.user.model.DeviceUpgradeFlagVO;
import com.wdb007.venus.web.api.user.model.OperPageQueryRequest;
import com.wdb007.venus.web.api.user.model.RankListRequest;
import com.wdb007.venus.web.api.user.model.RegisterRequest;
import com.wdb007.venus.web.api.user.model.RegisterResponse;
import com.wdb007.venus.web.api.user.model.ReportAbnormalRequest;
import com.wdb007.venus.web.api.user.model.UserActiveVO;
import com.wdb007.venus.web.api.user.model.UserDespositCashStatusVO;
import com.wdb007.venus.web.api.user.model.UserFamilyMemberVO;
import com.wdb007.venus.web.api.user.model.UserIsbnWishFlag;
import com.wdb007.venus.web.api.user.model.UserLastestInfoResponse;
import com.wdb007.venus.web.api.user.model.UserRankListVO;
import com.wdb007.venus.web.api.user.model.UserRankVO;
import com.wdb007.venus.web.api.user.model.UserRequest;
import com.wdb007.venus.web.api.user.model.UserWishInsertRequest;
import com.wdb007.venus.web.api.user.model.UserWishRemoveRequest;
import com.wdb007.venus.web.api.user.model.WishListRequest;
import com.wdb007.venus.web.api.user.model.WishListVO;
import com.wdb007.venus.web.api.user.model.ZhimaCreditRequest;
import com.wdb007.venus.web.api.utils.RegExpValidatorUtils;

@Controller
@RequestMapping("/user/")
public class UserController extends BaseController{

	private final static Logger logger = LoggerFactory.getLogger(UserController.class);
	
	@Autowired
	private BookInfoService bookInfoService;
	
	@Autowired
	private UserService userService ;
	
	@Autowired
	private BookgridService bookGridService;
	
	@Autowired
	private ConfigInfoManager configInfoManager;
	
	@Autowired
	private BookShelfService bookShelfService;
	
	
	/**
	 * 图书借阅历史查询
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/getBorrowList", method = RequestMethod.GET)
	@ResponseBody
	public BaseResponse getBorrowList(OperPageQueryRequest request)
	{
		logger.info("getBorrowList's request: {}", JSON.toJSONString(request));
		BaseResponse baseResponse = success();
		try {
			Long userid = request.getUserid();
			checkIsNull(request.getOper(), "oper");
			UserBorrowPageDTO userBorrowPageDTO = new UserBorrowPageDTO();
			userBorrowPageDTO.setUserid(userid);
			userBorrowPageDTO.setPagesize(request.getPagesize());
			userBorrowPageDTO.setOffset((request.getPageno()-1)* request.getPagesize());
			userBorrowPageDTO.setOper(request.getOper());
			BorrowedHistVO vo = bookInfoService.getBorrowList(userBorrowPageDTO);
			baseResponse.setTotalcount(vo.getTotalCount());
			baseResponse.setItems(vo.getList());
		}catch(Exception e) {
			logger.error(e.getMessage(), e);
			baseResponse = failed(e);
		}
		logger.info("getBorrowList's response: {}", JSON.toJSONString(baseResponse));
		return baseResponse ;
	}
	/**
	 * 在借图书列表查询
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/getBorrowingList", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse getBorrowingList(UserRequest request) {
		logger.info("在借图书列表查询getBorrowingList request: {}", JSON.toJSONString(request));
		BaseResponse baseResponse = success();
		try {
			BorrowingBookDTO borrowingBookDTO = userService.getBorrowingList(request.getUserid());
			if(null ==  borrowingBookDTO) {
				throw new BizException(RspCodeEnum.QUERY_LIST_IS_NULL);
			}
			BorrowingBookVO borrowingBookVo = new BorrowingBookVO();
			borrowingBookVo.setTotalcount(borrowingBookDTO.getTotalcount());
			for(BorrowingBook bb :borrowingBookDTO.getBorrowlist()) {
				
				com.wdb007.venus.web.api.book.model.BorrowingBook bbVo = new com.wdb007.venus.web.api.book.model.BorrowingBook();
				bbVo.setBorrow_date(bb.getBorrow_date());
				bbVo.setBorrowcount(bb.getBorrowcount());
				bbVo.setGrid_code(bb.getGrid_code());
				bbVo.setSerialnumber(bb.getSerialnumber());
				bbVo.setShelf_code(bb.getShelf_code());
				
				for(BRBookDTO brbook : bb.getBooks()) {
					BRBookVO brBookVo = new BRBookVO();
					brBookVo.setBookname(brbook.getBookname());
					brBookVo.setIsbn(brbook.getIsbn());
					brBookVo.setImgurl(brbook.getImgurl());
					bbVo.getBooks().add(brBookVo);
				}
				borrowingBookVo.getBorrowlist().add(bbVo);
			}
			baseResponse.setDetail(borrowingBookVo);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			baseResponse = failed(e);
		}
		logger.info("在借图书列表查询getBorrowingList response: {}", JSON.toJSONString(baseResponse));
		return baseResponse ;
	}
	/**
	 * 获取手机验证码
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/getRegisterCode", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse getRegisterCode(RegisterRequest request, HttpServletRequest httpRequest) {
		logger.info("获取手机验证码getRegisterCode request: {}", JSON.toJSONString(request));
		long startTime = System.currentTimeMillis();
		BaseResponse baseResponse = success();
		try {
			String version = httpRequest.getHeader("ver");
			SmsVerifactionDTO smsVerifaction = new SmsVerifactionDTO();
			checkIsNull(request.getMobile_no(), "手机号码");
			smsVerifaction.setMobileNo(request.getMobile_no());
			int status = userService.getRegisterCode(smsVerifaction, version);
			switch (status) {
			case 0:
				baseResponse.setCode(RspCodeEnum.SMS_SEND_SUCCESS.getRspCode());
				baseResponse.setMessage(RspCodeEnum.SMS_SEND_SUCCESS.getRspMsg());
				break;
			case 1:
				throw new BizException(RspCodeEnum.MOBILE_IS_UNVALID);
			case 2:
				throw new BizException(RspCodeEnum.SMS_SEND_FAILED);
			default:
				break;
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			baseResponse = failed(e);
		}
		logger.info("获取手机验证码getRegisterCode response: {},cust_time {}ms", JSON.toJSONString(baseResponse),(System.currentTimeMillis() - startTime));
		return baseResponse ;
	}
	
	/**
	 * 登陆接口
	 * @param httpRequest
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/login", method=RequestMethod.POST)
	@ResponseBody
	public BaseResponse login(HttpServletRequest httpRequest, RegisterRequest request){
		logger.info("login request: {}", JSON.toJSONString(request));
		logger.info("request.headers.X-Forwarded-For: {}", httpRequest.getHeader("X-Forwarded-For"));
		logger.info("request.remoteAddr: {}", httpRequest.getRemoteAddr());
		//登录时usertoken，为wx_user_relation表中的id
		String wxUserRelationId = httpRequest.getParameter("usertoken");
		BaseResponse baseResponse = success();
		baseResponse.setMessage("登陆成功");
		try {
			checkIsNull(request.getMobile_no(), "手机号码");
			checkIsNull(request.getVerify_code(), "短信验证码");
//			checkIsNull(request.getRegistration_id(), "极光关联ID");
			
			SmsVerifactionDTO smsVerifaction = new SmsVerifactionDTO();
			smsVerifaction.setMobileNo(request.getMobile_no());
			smsVerifaction.setSmsCode(request.getVerify_code());
			smsVerifaction.setRegistration_id(request.getRegistration_id());
			smsVerifaction.setVisitorId(request.getVisitorId());
			UserAccessLogDTO accessLog = new UserAccessLogDTO();
			accessLog.setPartner(httpRequest.getHeader("source"));
			logger.info("login source:{}",httpRequest.getHeader("source"));
			//活动请求的登录
			if(!isEmpty(httpRequest.getParameter("activityPartner"))) {
				accessLog.setPartner(httpRequest.getParameter("activityPartner"));
			}
			
			String ip = httpRequest.getHeader("X-Forwarded-For") ;
			if(null == ip || !RegExpValidatorUtils.isIP(ip)){
				ip = httpRequest.getRemoteAddr();
			}
			accessLog.setIp(ip);
			
			VenusSvcResp<UserEntiretyDTO> resp =  userService.login(smsVerifaction, accessLog, wxUserRelationId);
			if(resp.getRspCodeEnum() != null) {
				throw new BizException(resp.getRspCodeEnum());
			}
			//如果不是h5活动页，才判断Body
			if(isEmpty(httpRequest.getParameter("activityPartner"))) {
				if(resp.getBody().getInviteFlag() == 0) {
					baseResponse.setCode(2);
				}else if(resp.getBody().getInviteFlag() == 1) {
					baseResponse.setCode(1);
				}
			}else {
				logger.info("login response: {}", JSON.toJSONString(baseResponse));
				return baseResponse;
			}
			
			//3.注册/登录
			UserEntiretyDTO userEntiretyDTO = resp.getBody();
			RegisterResponse registerResponse = new RegisterResponse();
			BeanUtils.copyProperties(userEntiretyDTO, registerResponse);
			baseResponse.setDetail(registerResponse);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			baseResponse = failed(e);
		}
		logger.info("login response: {}", JSON.toJSONString(baseResponse));
		return baseResponse ;
	}
	
	
	
	/**
	 * 获取用户最新信息接口
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/getUserInfo", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse getUserInfo(UserRequest request) {
		logger.info("获取用户最新信息getUserInfo's 请求参数: {}", JSON.toJSONString(request));
		BaseResponse baseResponse = success();
		
		try {
			UserQueryDTO userQuery = new UserQueryDTO();
			userQuery.setUserid(request.getUserid());
			userQuery.setUsertoken(request.getUsertoken());
			VenusSvcResp<UserLastestInfoDTO> result = userService.getUserInfo(userQuery);
			UserLastestInfoDTO infoDTO = result.getBody();
			UserLastestInfoResponse response = new UserLastestInfoResponse();
			BeanUtils.copyProperties(infoDTO, response);
//			response.setRank(rankDTO.getRank_num()+"");
			baseResponse.setDetail(response);
		}catch (Exception e) {
			logger.error(e.getMessage(), e);
			baseResponse = failed(e);
		}
		logger.info("获取用户最新信息getUserInfo's 响应参数: {}", baseResponse);
		return baseResponse ;
	}
	/**
	 * 异常报修接口
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/reportAbnormal", method=RequestMethod.POST)
	@ResponseBody
	public BaseResponse reportAbnormal(ReportAbnormalRequest request) {
		logger.info("举报异常reportAbnormal's 请求参数: {}", JSON.toJSONString(request));
		BaseResponse response = success();
		
		try {
//			checkIsNull(request.getDescribe(), "describe");
			Integer maintain_type = request.getMaintain_type();
			if(null == maintain_type) {
				maintain_type = 20;
				request.setMaintain_type(maintain_type);
			}
			ReportAbnormalDTO reportAbnormalDTO = new ReportAbnormalDTO();
			BeanUtils.copyProperties(request, reportAbnormalDTO);
			String imgUrls = request.getImgUrls();
			if(!ObjectUtils.isEmpty(imgUrls)) {
				String[] arr = imgUrls.split(",");
				reportAbnormalDTO.setImgUrlArr(arr);
			}
			
			
			userService.reportAbnormal(reportAbnormalDTO);
		} catch (Exception e) {
			logger.error("系统处理异常", e);
			response = failed(e);
		}
		logger.info("举报异常reportAbnormal's 响应参数: {}", JSON.toJSONString(response));
		return response ;
	}
	/**
	 * 意见反馈接口
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/feedback", method=RequestMethod.POST)
	@ResponseBody
	public BaseResponse feedback(ReportAbnormalRequest request) {
		logger.info("意见反馈feedback's 请求参数: {}", JSON.toJSONString(request));
		BaseResponse response = success();
		try {
			checkIsNull(request.getDescribe(), "describe");
			ReportAbnormalDTO reportAbnormalDTO = new ReportAbnormalDTO();
			BeanUtils.copyProperties(request, reportAbnormalDTO);
			userService.feedback(reportAbnormalDTO);
		} catch (Exception e) {
			logger.error("系统处理异常", e);
			response = failed(e);
		}
		logger.info("意见反馈feedback's 响应参数: {}", JSON.toJSONString(response));
		return response ;
	}
	/**
	 * 注销接口
	 * @param httpRequest
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/logout", method=RequestMethod.POST)
	@ResponseBody
	public BaseResponse logout(HttpServletRequest httpRequest, UserRequest request) {
		logger.info("登出注销logout's 请求参数: {}", JSON.toJSONString(request));
		logger.info("request.headers.X-Forwarded-For: {}", httpRequest.getHeader("X-Forwarded-For"));
		logger.info("request.remoteAddr: {}", httpRequest.getRemoteAddr());
		BaseResponse response = success();
		try {
			UserAccessLogDTO accessLog = new UserAccessLogDTO();
			String ip = httpRequest.getHeader("X-Forwarded-For") ;
			if(null == ip || !RegExpValidatorUtils.isIP(ip)){
				ip = httpRequest.getRemoteAddr();
			}
			accessLog.setIp(ip);
			accessLog.setUserid(request.getUserid());
			userService.logout(accessLog);
		} catch (Exception e) {
			logger.error("系统处理异常", e);
			response = failed(e);
		}
		logger.info("登出注销logout's 响应参数: {}", JSON.toJSONString(response));
		return response ;
	}
	
	@RequestMapping(value="/active", method=RequestMethod.POST)
	@ResponseBody
	public BaseResponse active(ActiveRequest request){
		BaseResponse response = success();
		logger.info("设备启动激活的请求参数: {}", JSON.toJSONString(request));
		String guid = null ;
		try {
			UserActiveDTO activeDTO = new UserActiveDTO();
			BeanUtils.copyProperties(request, activeDTO);
			VenusSvcResp<String> venusResp = userService.equipActive(activeDTO);
			guid = venusResp.getBody();
			if(null == guid) {
				throw new BizException(RspCodeEnum.ACTIVE_DATAVER_IS_INVALID);
			}
			if(venusResp.getRspCodeEnum() != null) {
				throw new BizException(venusResp.getRspCodeEnum());
			}
			UserActiveVO vo = new UserActiveVO();
			vo.setGuid(guid);
			response.setDetail(vo);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		
		logger.info("设备启动激活的响应参数: {}", JSON.toJSONString(response));
		return response ;
	}
	
	@RequestMapping(value="/activeStatus", method = RequestMethod.POST)
	@ResponseBody
	public BaseResponse activeStatus(ActiveRequest request) {
		BaseResponse response = success();
		logger.info("设备激活状态变更的请求参数: {}", JSON.toJSONString(request));
		try {
			UserActiveDTO activeDTO = new UserActiveDTO();
			BeanUtils.copyProperties(request, activeDTO);
			String guid = userService.equipActiveStatus(activeDTO);
			if(guid == null) {
				throw new BizException(RspCodeEnum.ACTIVE_DEVICETOEKN_IS_NOT_EXISTS);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		
		logger.info("设备激活状态变更的响应参数: {}", JSON.toJSONString(response));
		return response ;
	}
	
	@RequestMapping(value="/queryWishList", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse queryWishList(WishListRequest request) {
		BaseResponse response = success();
		logger.info("心愿单列表queryWishList的请求参数: {}", JSON.toJSONString(request));
		try {
			WishListPageQueryDTO pageQueryDTO = new WishListPageQueryDTO();
			checkIsNull(request.getShelf_code(), "shelf_code");
			checkIsNull(request.getOper(), "oper");
			pageQueryDTO.setUserid(request.getUserid());
			pageQueryDTO.setPagesize(request.getPagesize());
			pageQueryDTO.setOffset((request.getPageno()-1)* request.getPagesize());
			pageQueryDTO.setShelfCode(request.getShelf_code());
			pageQueryDTO.setOper(request.getOper());
			WishListPageResultDTO result = userService.queryWishList(pageQueryDTO);
			response.setTotalcount(result.getTotalcount());
			List<WishListVO> list = new ArrayList<WishListVO>();
			for(WishListDTO dto : result.getWishList()) {
				WishListVO vo = new WishListVO();
				BeanUtils.copyProperties(dto, vo);
				list.add(vo);
			}
			response.setItems(list);
		}catch(Exception e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		logger.info("心愿单列表queryWishList的响应参数: {}", JSON.toJSONString(response));
		return response ;
	}
	
	@RequestMapping(value="/queryWishListV2", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse queryWishListV2(WishListRequest request) {
		BaseResponse response = success();
		logger.info("心愿单列表queryWishListV2的请求参数: {}", JSON.toJSONString(request));
		try {
			checkIsNull(request.getShelf_code(), "shelf_code");
			WishListPageQueryDTO pageQueryDTO = new WishListPageQueryDTO();
			pageQueryDTO.setShelfCode(request.getShelf_code());
			pageQueryDTO.setUserid(request.getUserid());
			List<WishListResultDTO> dtoList = userService.queryWishListV2(pageQueryDTO );
			response.setItems(dtoList);
		}catch(Exception e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		logger.info("心愿单列表queryWishListV2的响应参数: {}", JSON.toJSONString(response));
		return response ;
	}
	
	@RequestMapping(value="/removeWishBook", method=RequestMethod.POST)
	@ResponseBody
	public BaseResponse removeWishBook(UserWishRemoveRequest request) {
		BaseResponse response = success();
		logger.info("删除心愿单图书removeWishBook的请求参数: {}", JSON.toJSONString(request));
		try {
			userService.removeWishBook(request.getId(), request.getUserid(), request.getIsbn());
		}catch(Exception e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		logger.info("删除心愿单图书removeWishBook的响应参数: {}", JSON.toJSONString(response));
		return response ;
	}
	
	@RequestMapping(value="/saveWishBook", method=RequestMethod.POST)
	@ResponseBody
	public BaseResponse saveWishBook(UserWishInsertRequest request) {
		BaseResponse response = success();
		logger.info("加入心愿单saveWishBook的请求参数: {}", JSON.toJSONString(request));
		try {
			String isbn = request.getIsbn();
			Long userId = request.getUserid();
			checkIsNull(isbn, "isbn");
			userService.saveWishBook(userId, isbn);
		}catch(Exception e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		logger.info("加入心愿单saveWishBook的响应参数: {}", JSON.toJSONString(response));
		return response ;
	}
	
	@RequestMapping(value="/getIsbnWishFlag", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse getIsbnWishFlag(UserWishInsertRequest request) {
		BaseResponse response = success();
		logger.info("获取图书是否加入心愿单标志getIsbnWishFlag的请求参数: {}", JSON.toJSONString(request));
		try {
			String isbn = request.getIsbn();
			Long userId = request.getUserid();
			checkIsNull(isbn, "isbn");
			int flag = userService.getIsbnWishFlag(isbn, userId);
			UserIsbnWishFlag wishFlag = new UserIsbnWishFlag();
			wishFlag.setFavorite(flag);
			response.setDetail(wishFlag);
		}catch(Exception e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		logger.info("获取图书是否加入心愿单标志getIsbnWishFlag的响应参数: {}", JSON.toJSONString(response));
		return response ;
	}
	/**
	 * 
	 * @Method:getRankingList
	 * @Description:
	 * @Time 2017年10月25日 下午2:19:55
	 * @author: Tom
	 * @return
	 */
	@RequestMapping(value="/queryRankList", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse getRankingList(RankListRequest request) {
		BaseResponse response = success();
		logger.info("排行榜列表queryRankList的请求参数: {}", JSON.toJSONString(request));
		try {
			
			checkIsNull(request.getOper(), "oper");
			RankListPageQueryDTO pageQueryDTO = new RankListPageQueryDTO();
			pageQueryDTO.setPagesize(request.getPagesize());
			pageQueryDTO.setOffset((request.getPageno() - 1) * request.getPagesize());
			pageQueryDTO.setOper(request.getOper());
			//
			Long userId = request.getUserid();
			RankListPageResultDTO result = userService.queryRankList(pageQueryDTO, userId);
			response.setTotalcount(result.getTotalcount());
			List<UserRankListVO> userRankList = new ArrayList<UserRankListVO>();
			int i=1;
			int pageNo = request.getPageno();
			for (UserRankDTO dto : result.getRankList()) {
				UserRankListVO vo = new UserRankListVO();
				vo.setRank_num(((pageNo-1)*10+i)+"");
				BeanUtils.copyProperties(dto, vo);
				userRankList.add(vo);
				i++;
			}
			response.setItems(userRankList);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		logger.info("排行榜列表queryRankList的响应参数: {}", JSON.toJSONString(response));
		return response;
	}
	@RequestMapping(value="/queryUserRank", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse getUserRank(RankListRequest request) {
		BaseResponse response = success();
		logger.info("个人排行信息queryUserRank的请求参数: {}", JSON.toJSONString(request));
		try {
			checkIsNull(request.getOper(), "oper");
			Long userId = request.getUserid();
			RankListPageQueryDTO pageQueryDTO = new RankListPageQueryDTO();
			pageQueryDTO.setOper(request.getOper());
			UserRankDTO result = userService.queryUserRank(pageQueryDTO,userId);
			UserRankVO userRankVO = new UserRankVO();
			BeanUtils.copyProperties(result, userRankVO);
			response.setDetail(userRankVO);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		logger.info("个人排行信息queryUserRank的响应参数: {}", JSON.toJSONString(response));
		return response;
	}
	
	@RequestMapping(value="/queryUserDepositAmount", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse queryUserDepositAmount(UserRequest request) {
		BaseResponse response = success();
		logger.info("查询用户余额以及押金接口queryUserDepositAmount的请求参数: {}", JSON.toJSONString(request));
		try {
			//1.解析秘钥字符串
			String bookcaseId = request.getBookcaseId();
			String shelfCode = "";
			if(null != bookcaseId){
				checkIsNull(bookcaseId, "bookcaseId");
				if(bookcaseId.startsWith("0021")){
					shelfCode = bookcaseId;
				}else{
					shelfCode = userService.aesDecrypt(bookcaseId);
				}
			}
			String model = bookShelfService.getModel(shelfCode);
			//2.判断用户是否被锁定
			boolean locked = userService.isLocked(request.getUserid());
			if(locked) {
				throw new BizException(RspCodeEnum.USER_IS_LOCKED);
			}
			UserDespositCashStatusVO vo = new UserDespositCashStatusVO();
			UserDespositCashStatusDTO statusDTO = userService.queryUserDepositAmount(request.getUserid());			
			BeanUtils.copyProperties(statusDTO, vo);
			//3.判断该图书在哪个书格中
			String gridCode = null ;
			if(!ObjectUtils.isEmpty(request.getIsbn())) {
				gridCode = bookGridService.getGridCodeByIsbn(shelfCode, request.getIsbn());
				if(ObjectUtils.isEmpty(gridCode)) {
					vo.setType(1);
					vo.setTip("很遗憾，你选的书已经借走啦，您可返回首页选阅其他书籍。");
				}
			}
			String requestGridCode = request.getGrid_code();
			if(!ObjectUtils.isEmpty(requestGridCode)) {
				boolean isIn = bookGridService.gridIsInShelf(requestGridCode, shelfCode);
				if(!isIn) {
					vo.setType(2);
					vo.setTip("您扫码的书柜和当前书柜不一致，请返回借书架重新扫码借阅。");
				}else {
					gridCode = requestGridCode;
				}
			}
			vo.setModel(model);
			vo.setShelf_code(shelfCode);
			vo.setGrid_code(gridCode);
			response.setDetail(vo);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			response = failed(e);
		}
		
		logger.info("查询用户余额以及押金接口queryUserDepositAmount的响应参数: {}", JSON.toJSONString(response));
		return response;
	}
	
	@RequestMapping(value="/updateUserInfo", method=RequestMethod.POST)
	@ResponseBody
	public BaseResponse updateUserInfo(HttpServletRequest request) {
		logger.info("updateUserInfo....start");
		BaseResponse response = success();
		try {
			UserInfoDTO infoDTO = new UserInfoDTO();
			String imgurl = request.getParameter("imgurl");
			if(!ObjectUtils.isEmpty(imgurl)) {
				byte [] imgData = Base64.decodeBase64(imgurl);
				String url = userService.uploadUserHead(imgData);
				infoDTO.setImgurl(url);
			}
			infoDTO.setId(Long.valueOf(request.getParameter("userid")));

			if(!ObjectUtils.isEmpty(request.getParameter("username"))) {
				infoDTO.setUserName(request.getParameter("username").trim());
			}
			userService.updateUserInfo(infoDTO);
		} catch (Exception e) {
			response = failed(e);
			logger.error(e.getMessage(), e);
		}
		
		
		logger.info("更新用户信息接口updateUserInfo的响应参数: {}", JSON.toJSONString(response));
		return response;
	}
	
	
	@RequestMapping(value="/getFamilyMembers", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse getFamilyMembers(UserRequest request) {
		BaseResponse response = success();
		logger.info("获取家庭成员列表接口getFamilyMembers的请求参数: {}", JSON.toJSONString(request));
		try {
			List<UserFamilyMemberDTO> dtoList = userService.getFamilyMembers(request.getUserid());
			
			List<UserFamilyMemberVO> voList = new ArrayList<UserFamilyMemberVO>();
			for(UserFamilyMemberDTO dto: dtoList) {
				UserFamilyMemberVO vo = new UserFamilyMemberVO();
				vo.setBirth(dto.getBirth());
				vo.setGender(dto.getGender());
				vo.setId(dto.getId());
				vo.setImgurl(dto.getImgurl());
				vo.setMembername(dto.getMemberName());
				vo.setMembertype(dto.getMemberType());
				vo.setMobileno(dto.getMobileNo());
				vo.setUsername(dto.getUserName());
				vo.setUserid(dto.getUserId());
				voList.add(vo);
			}
			response.setItems(voList);
		} catch (Exception e) {
			response = failed(e);
			logger.error(e.getMessage(), e);
		}
		logger.info("获取家庭成员列表接口getFamilyMembers的响应参数: {}", JSON.toJSONString(response));
		return response;
	}
	
	@RequestMapping(value="/updateFamilyMember", method=RequestMethod.POST)
	@ResponseBody
	public BaseResponse updateFamilyMember(HttpServletRequest request) {
		BaseResponse response = success();
		logger.info("更新用户信息接口updateFamilyMemeber start...........");
		try {
			String imgurl = request.getParameter("imgurl");
			checkIsNull(request.getParameter("id"), "id");
			checkIsNull(request.getParameter("membertype"), "membertype");
			UserFamilyMemberDTO member = new UserFamilyMemberDTO();
			if(!ObjectUtils.isEmpty(imgurl)) {
				byte [] imgData = Base64.decodeBase64(imgurl);
				String url = userService.uploadUserHead(imgData);
				member.setImgurl(url);
			}
			if(!ObjectUtils.isEmpty(request.getParameter("username"))) {
				member.setUserName(request.getParameter("username").trim());
			}
			if(!ObjectUtils.isEmpty(request.getParameter("id"))) {
				member.setId(Long.valueOf(request.getParameter("id").trim()));
			}
			
			if(!ObjectUtils.isEmpty(request.getParameter("gender"))) {
				member.setGender(Integer.valueOf(request.getParameter("gender").trim()));
			}
			if(!ObjectUtils.isEmpty(request.getParameter("mobileno"))) {
				member.setMobileNo((request.getParameter("mobileno").trim()));
			}
			
			if(!ObjectUtils.isEmpty(request.getParameter("birth"))) {
				member.setBirth((request.getParameter("birth").trim()));
			}
			
			if(!ObjectUtils.isEmpty(request.getParameter("membername"))) {
				member.setMemberName(Integer.valueOf(request.getParameter("membername").trim()));
			}
			if(!ObjectUtils.isEmpty(request.getParameter("membertype"))) {
				member.setMemberType(Integer.valueOf(request.getParameter("membertype").trim()));
			}
			member.setUserId(Long.valueOf(request.getParameter("userid")));
			userService.updateUserFamilyMember(member);
		} catch (Exception e) {
			response = failed(e);
			logger.error(e.getMessage(), e);
		}
		logger.info("更新用户信息接口updateFamilyMemeber的响应参数: {}", JSON.toJSONString(response));
		return response;
	}
	
	@RequestMapping(value="/addFamilyMember", method=RequestMethod.POST)
	@ResponseBody
	public BaseResponse addFamilyMember(HttpServletRequest request) {
		BaseResponse response = success();
		logger.info("新增家庭成员接口addFamilyMemeber start...........");
		try {
			checkIsNull(request.getParameter("membertype"), "membertype");
			checkIsNull(request.getParameter("username"), "username");
			String imgurl = request.getParameter("imgurl");
			UserFamilyMemberDTO member = new UserFamilyMemberDTO();
			if(!ObjectUtils.isEmpty(imgurl)) {
				byte [] imgData = Base64.decodeBase64(imgurl);
				String url = userService.uploadUserHead(imgData);
				member.setImgurl(url);
			}else {
				member.setImgurl(configInfoManager.getValue("head_img_default"));
			}
			if(!ObjectUtils.isEmpty(request.getParameter("username"))) {
				member.setUserName(request.getParameter("username").trim());
			}
			
			if(!ObjectUtils.isEmpty(request.getParameter("gender"))) {
				member.setGender(Integer.valueOf(request.getParameter("gender").trim()));
			}
			if(!ObjectUtils.isEmpty(request.getParameter("mobileno"))) {
				member.setMobileNo((request.getParameter("mobileno").trim()));
			}
			
			if(!ObjectUtils.isEmpty(request.getParameter("birth"))) {
				member.setBirth((request.getParameter("birth").trim()));
			}
			
			if(!ObjectUtils.isEmpty(request.getParameter("membername"))) {
				member.setMemberName(Integer.valueOf(request.getParameter("membername").trim()));
			}
			if(!ObjectUtils.isEmpty(request.getParameter("membertype"))) {
				member.setMemberType(Integer.valueOf(request.getParameter("membertype").trim()));
			}
			member.setUserId(Long.valueOf(request.getParameter("userid")));
			userService.addUserFamilyMember(member);
		} catch (Exception e) {
			response = failed(e);
			logger.error(e.getMessage(), e);
		}
		
		
		
		logger.info("新增家庭成员接口addFamilyMemeber的响应参数: {}", JSON.toJSONString(response));
		return response;
	}
	
	@RequestMapping(value="/getUpgradeFlag", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse getUpgradeFlag(DeviceTypeRequest request) {
		BaseResponse response = success();
		logger.info("获取设备是否更新标志getUpgradeFlag的请求参数: {}", JSON.toJSONString(request));
		try {
			checkIsNull(request.getDevice_type(), "device_type");
			checkIsNull(request.getVersion(), "version");
			DeviceUpgradeFlagDTO flag = userService.getUpgrade(request.getDevice_type(), request.getVersion());
			DeviceUpgradeFlagVO deviceUpgradeFlag = new DeviceUpgradeFlagVO();
			BeanUtils.copyProperties(flag, deviceUpgradeFlag);
			response.setDetail(deviceUpgradeFlag);
		} catch (Exception e) {
			response = failed(e);
			logger.error(e.getMessage(), e);
		}
		logger.info("获取设备是否更新标志getUpgradeFlag的响应: {}", JSON.toJSONString(response));
		return response;
	}
	
	@RequestMapping(value="/getUserVIPEndDate", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse getUserVIPEndDate(String mobile_no){
		BaseResponse response = success();
		logger.info("获取用户vip月卡到期时间's mobile_no:[{}]", mobile_no);
		try{
			checkIsNull(mobile_no, "mobile_no");
			String endDate = userService.getUserVIPEndDate(mobile_no);
			Map<String, String> map = new HashMap<String, String>();
			map.put("end_date", endDate);
			response.setDetail(map);
		}catch(Exception e){
			response = failed(e);
			logger.error(e.getMessage(), e);
		}
		logger.info("获取用户vip月卡到期时间的响应: {}", JSON.toJSONString(response));
		return response;
	}
	
	@RequestMapping(value="/getUserInfoByWx", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse getUserInfoByWx(HttpServletRequest request) {
		BaseResponse baseResponse = success();
		String appid = request.getParameter("appid");
		String openid = request.getParameter("openid");
		logger.info("getUserInfoByWx's appid: {}, openid: {}", appid, openid);
		try{
			VenusSvcResp<UserLastestInfoDTO> resp = userService.getUserInfoByWx(openid, appid);
			baseResponse.setDetail(resp.getBody());
		}catch(Exception e) {
			baseResponse = failed(e);
			logger.error(e.getMessage(), e);
		}
		logger.info("getUserinfoByWx's response: {}", JSON.toJSONString(baseResponse));
		return baseResponse;
	}
	
	@RequestMapping(value="/getInviteInfo", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse getInviteInfo(UserRequest request) {
		BaseResponse baseResponse = success();
		logger.info("getInviteInfo's request: {}", JSON.toJSONString(request));
		try{
			UserInviteInfoDTO inviteInfo = userService.getInviteInfo(request.getUserid());
			baseResponse.setDetail(inviteInfo);
		}catch(Exception e) {
			baseResponse = failed(e);
			logger.error(e.getMessage(), e);
		}
		logger.info("getInviteInfo's response: {}", JSON.toJSONString(baseResponse));
		return baseResponse;
	}
	
	@RequestMapping(value="/queryWeekRankList", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse queryWeekRankList(UserRequest request) {
		BaseResponse baseResponse = success();
		logger.info("queryWeekRankList's request: {}", JSON.toJSONString(request));
		try {
			List<WeekRankInfoDTO> list = userService.queryWeekRankList();
			baseResponse.setItems(list);
		}catch(Exception e) {
			baseResponse = failed(e);
			logger.error(e.getMessage(), e);
		}
		logger.info("queryWeekRankList's response: {}", JSON.toJSONString(baseResponse));
		return baseResponse;
	}
	
	@RequestMapping(value="/queryPersonInWeekRank", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse queryPersonInWeekRank(UserRequest request) {
		BaseResponse baseResponse = success();
		logger.info("queryPersonInWeekRank's request: {}", JSON.toJSONString(request));
		try {
			WeekRankInfoDTO weekRank = userService.queryPersonInWeekRank(request.getUserid());
			//添加分享的图片
			WeekRankPersonInfoDTO  weekRankPersonInfo = new WeekRankPersonInfoDTO();
			BeanUtils.copyProperties(weekRank, weekRankPersonInfo);
			int nextCount = 1;
			//当前排行昵称
			Map<String, Object> curRankMap = userService.selectCurrentTitleByRead(weekRank.getBook_count());
			int nextSort = 1;
			logger.info("readCount{}",curRankMap.get("readCount"));
			if(!ObjectUtils.isEmpty(curRankMap.get("readCount"))) {
				nextSort = new Integer(curRankMap.get("readCount").toString()) + 1;
			}
			//下一个排行昵称
			Map<String, Object> nextRankMap = userService.readTitleMappingName(nextSort);
			logger.info("readCount{}", nextRankMap.get("maxRead"));
			nextCount = new Integer(nextRankMap.get("maxRead").toString()) - weekRank.getBook_count();
			if(nextCount < 1) nextCount = 1;
			String nextRankTilte = nextRankMap.get("title").toString();
			String shareUrl = ShareImageUtil.getShareImgUrl(weekRank.getBook_count()+"", weekRank.getRank()+"", nextCount+"" , nextRankTilte, request.getUserid(), weekRank.getImgurl());
			weekRankPersonInfo.setShareUrl(shareUrl);
			weekRankPersonInfo.setRankTitle(curRankMap.get("title").toString());
			baseResponse.setDetail(weekRankPersonInfo);
		}catch(Exception e) {
			baseResponse = failed(e);
			logger.error(e.getMessage(), e);
		}
		logger.info("queryPersonInWeekRank's response: {}", JSON.toJSONString(baseResponse));
		return baseResponse;
	}
	
	@RequestMapping(value="/zhimaCredit", method=RequestMethod.POST)
	@ResponseBody
	public BaseResponse zhimaCredit(ZhimaCreditRequest request) {
		logger.info("zhimaCredit's request: {}", JSON.toJSONString(request));
		BaseResponse baseResponse= success();
		try {
			checkIsNull(request.getCertNo(), "certNo");
			checkIsNull(request.getRealName(), "realName");
			String zhimaAdmittance = userService.zhimaAdmittance(request.getUserid(), request.getCertNo(), request.getRealName());
			Map<String, String> map = new HashMap<String, String>();
			map.put("admittanceFlag", zhimaAdmittance);
			baseResponse.setDetail(map);
		}catch(Exception e) {
			baseResponse = failed(e);
			logger.error(e.getMessage(), e);
		}
		
		logger.info("zhimaCredit's response: {}", JSON.toJSONString(baseResponse));
		return baseResponse;
	}
	
//	@RequestMapping(value="/getMobileNo", method=RequestMethod.GET)
//	@ResponseBody
//	public BaseResponse getMobileNo(String usertoken) {
//		BaseResponse baseResponse = success();
//		logger.info("getMobileNo request: {}", usertoken);
//		try {
//			checkIsNull(usertoken, "usertoken");
//			String mobileNo = userService.getMobile(usertoken);
//			Map<String, String> map = new HashMap<String, String>();
//			map.put("mobile_no", mobileNo);
//			baseResponse.setDetail(map);
//		}catch(Exception e) {
//			baseResponse = failed(e);
//			logger.error(e.getMessage(), e);
//		}
//		
//		logger.info("getMobileNo response: {}", usertoken);
//		return baseResponse;
//		
//	}
}
